package com.hilon.foundation.query;

import com.alibaba.fastjson2.JSON;
import com.hilon.foundation.util.ResultBean;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

public abstract class QueryBaseServiceImpl<T>  {

    protected final EntityManager entityManager;

    protected String entityName;

    protected QueryBaseServiceImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Transactional
    public ResultBean<String> submitSelectedRows(List<T> list, String curUser) {
        try {
            String resultListJsonString = JSON.toJSONString(list);
            System.out.println(resultListJsonString);
            System.out.println(curUser);
            //不良品抛转出各类处理单据 -- 一次执行更新和抛单
            Query storedProcedure = entityManager.createNativeQuery("call submit"+entityName+"(?,?)");
            storedProcedure.setParameter(1, resultListJsonString);
            storedProcedure.setParameter(2, curUser);
            storedProcedure.executeUpdate();
            return new ResultBean<>("成功提交数据");
        } catch (Exception e) {
            return new ResultBean<>(500, entityName+" submitSelectedRows 执行异常" + e.getMessage());
        }
    }

    @Transactional
    public ResultBean<String> deleteById(Long id) {
        try {
            //不良品抛转出各类处理单据 -- 一次执行更新和抛单
            Query storedProcedure = entityManager.createNativeQuery("delete from "+entityName+"  where id=?1");
            storedProcedure.setParameter(1, id);
            storedProcedure.executeUpdate();
            return new ResultBean<>("成功删除");
        } catch (Exception e) {
            return new ResultBean<>(500, entityName+" deleteById 执行异常" + e.getMessage());
        }
    }
    @Transactional
    public ResultBean<String> copyById(Long id) {
        try {
            //不良品抛转出各类处理单据 -- 一次执行更新和抛单
            Query storedProcedure = entityManager.createNativeQuery("call copyById"+entityName+"(?)");
            storedProcedure.setParameter(1, id);
            storedProcedure.executeUpdate();
            return new ResultBean<>("成功复制");
        } catch (Exception e) {
            return new ResultBean<>(500, entityName+" copyById 执行异常" + e.getMessage());
        }
    }
}
